#include "widget.h"
#include "ui_widget.h"
#include "qdesktopwidget.h"
#include "qlabel.h"
#include "qdebug.h"
#include "qstyleoption.h"
#include "qpainter.h"
#include "cfg.h"
#include <QDateTime>
#include "QTime"
#include <cmath>
#define PI (3.1415926)

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_TransparentForMouseEvents,true);
    QObject::connect(&m_timer,SIGNAL(timeout()),this,SLOT(RePaintWaterMark()));
}

void Widget::RePaintWaterMark()
{
    repaint();
}
void Widget::InitWaterMark()
{
    QDesktopWidget* desktop = QApplication::desktop();
    h = desktop->height();
    w = desktop->width();
    this->resize(w, h);

    Qt::WindowFlags m_flags = windowFlags();
    setWindowFlags(m_flags | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);

    configFile cfg;

    QString qstrFileName = (QApplication::applicationDirPath() + "/config/" + QApplication::applicationName() + ".cfg");
    if (!cfg.InitFile(qstrFileName))
    {
        qDebug() << " file is not exist,%1" << qstrFileName;
        exit(0);
    }
    m_nR =255; cfg.Get("watermark", "R").toInt();
    m_nG =255; cfg.Get("watermark", "G").toInt();
    m_nB =255; cfg.Get("watermark", "B").toInt();
    m_nRotate = -45;
    m_fOpacity = 0.3;
    m_nPointSize = cfg.Get("watermark", "size").toInt();
    m_strShowText = cfg.Get("watermark", "text").toString();
    m_timer.start(1000);
}


void  Widget::paintEvent(QPaintEvent *p1)
{
    QPainter p(this);
    QFont font;
    font.setPointSize(m_nPointSize);
    font.setFamily("Times New Roman");
    font.setLetterSpacing(QFont::AbsoluteSpacing, 0);
    p.setFont(font);
    QPen pen;
    pen.setColor(QColor(m_nR, m_nG, m_nB));
    p.setPen(pen);
    p.setOpacity(m_fOpacity);

    QDateTime current_date_time=QDateTime::currentDateTime();
    QString current_date=current_date_time.toString(" yyyy-MM-dd hh:mm:ss");
    QString showText=m_strShowText+current_date;
    p.rotate(m_nRotate);
    int tap_w=w/3;
    int tap_h=h/4;
    for (int i=0;i<h;i+=tap_h)
    {
        for(int j=-1*tap_w*2;j<w;j+= tap_w)
        {
            int x = j;
            int y = i;
            int x1 = j;
            int y1 = i;
            if (m_nRotate!=0)
            {
                int Ro=360+m_nRotate;
                x1 = x * cos(Ro * PI / 180.0f) + y * sin(Ro * PI / 180.0f);
                y1 = -x * sin(Ro * PI / 180.0f) + y * cos(Ro * PI / 180.0f);
            }
            p.drawText(x1, y1, tap_w, tap_h,0, showText);
        }
    }

}
Widget::~Widget()
{
    delete ui;
}

